package com.my.netty.basic;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class HelloNettyClient {
    public static void main(String[] args) throws InterruptedException {
        //1.创建客户端启动器，添加组件
        new Bootstrap()
            //2.添加eventLoop
            .group(new NioEventLoopGroup())
            //3.指定客户端SocketChannel实现类
            .channel(NioSocketChannel.class)
            //4.添加ChannelHandler，连接建立后会调用ChannelInitializer
            .handler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel sc) throws Exception {
                    //连接建立后会执行该方法，添加一个StringEncoder，将String转为ByteBuf
                    sc.pipeline().addLast(new StringEncoder());
                }
            })
            //5.连接服务器
            .connect(new InetSocketAddress("localhost", 8080))
            //sync是阻塞方法，在链接建立后才向下执行
            .sync()
            //连接建立好之后通过channel可拿到连接对象
            .channel()
            //6.向服务器发送数据；每次调用read/write方法都会自动调用ChannelHandler，本例中为StringEncoder
            .writeAndFlush("hello netty");

    }
}
